package com.bianguo.android.tencentpushdemo.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.bianguo.android.tencentpushdemo.entity.ItemData;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/9/14.
 */

public class DBHelper extends SQLiteOpenHelper {

    public static int DB_VERSION = 1;
    private final String[] FROM_ITEM_DATA = {"_id", "content", "imageId", "position"};

    public DBHelper(Context context, int version) {
        super(context, "tencentPush.db", null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table t_home_item(_id integer primary key autoincrement, content varchar(20), imageId integer, position integer)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion) {
            db.execSQL("drop table if exists t_order");
            onCreate(db);
        }
    }

    public void updateItemData(SQLiteDatabase db, ItemData itemData) {
        String where = "_id = " + itemData.getId();
        ContentValues values = new ContentValues();
        values.put("content", itemData.getContent());
        values.put("imageId", itemData.getImageId());
        values.put("position", itemData.getIndex());
        db.update("t_home_item", values, where, null);
        db.close();
    }

    public void deleteItem(SQLiteDatabase db, ItemData itemData) {
        db.execSQL("delete from t_home_item where _id = " + itemData.getId());
        db.close();
    }

    public void deleteAll(SQLiteDatabase db) {
        db.execSQL("delete from t_home_item");
        db.close();
    }

    public void insertItem(SQLiteDatabase db, ItemData itemData) {
        ContentValues values = new ContentValues();
        values.put("content", itemData.getContent());
        values.put("imageId", itemData.getImageId());
        values.put("position", itemData.getIndex());
        db.insert("t_home_item", null, values);
        db.close();
    }

    public ArrayList<ItemData> getItemDatas(SQLiteDatabase db) {
        ArrayList<ItemData> itemDatas = new ArrayList<>();
        Cursor cursor = db.query("t_home_item", FROM_ITEM_DATA, null, null, null, null, "position asc");
        while (cursor.moveToNext()) {
            ItemData itemData = new ItemData();
            itemData.setId(cursor.getInt(cursor.getColumnIndex("_id")));
            itemData.setContent(cursor.getString(cursor.getColumnIndex("content")));
            itemData.setImageId(cursor.getInt(cursor.getColumnIndex("imageId")));
            itemData.setIndex(cursor.getInt(cursor.getColumnIndex("position")));
            itemDatas.add(itemData);
        }
        db.close();
        return itemDatas;
    }
}
